﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Syngine.Components
{
	public sealed class FpsCounter : Drawable
	{
		private const float UpdateInterval = 1.0f;
		private float _timeSinceLastUpdate;
		private float _frameCount;
		private float _fps;
		private readonly string _assetName;
		private SpriteFont _font;
		private readonly Color _color;

		public FpsCounter()
		{
		}

		public FpsCounter(string assetName, Vector2 position) : this(assetName, position, Color.White)
		{
		}

		public FpsCounter(string assetName, Vector2 position, Color color)
		{
			Position = position;
			_assetName = assetName;
			_color = color;
		}

		/// <summary>
		/// The frames per second.
		/// </summary>
		public float FPS
		{
			get
			{
				return _fps;
			}
		}

		public override void LoadContent(LoadContext context)
		{
			if (!string.IsNullOrEmpty(_assetName))
			{
				_font = context.Load<SpriteFont>(_assetName);
			}
		}

		public override void UnloadContent()
		{
		}

		protected override void UpdateCore(UpdateContext context)
		{
			_timeSinceLastUpdate += (float)context.GameTime.ElapsedGameTime.TotalSeconds;

			_frameCount++;

			if (_timeSinceLastUpdate > UpdateInterval)
			{
				//mean fps over updateInterval
				_fps = _frameCount / _timeSinceLastUpdate;
				_frameCount = 0;
				_timeSinceLastUpdate -= UpdateInterval;
			}
		}

		protected override void DrawCore(DrawContext context)
		{
			if (_font != null)
			{
				context.DrawString(_font, "FPS: " + FPS, Position, _color);
			}
		}
	}
}
